package com.piece.admin.controller.system;

import com.piece.admin.controller.ControllerSupport;
import com.piece.admin.model.TbSysConfig;
import com.piece.admin.service.TbSysConfigService;
import com.piece.admin.support.SiteConfigSupport;
import com.piece.core.framework.annotation.permission.AclPermission;
import com.piece.core.framework.annotation.permission.SubmitPermission;
import com.piece.core.framework.constant.ExceptionConstants;
import com.piece.core.framework.enums.OptionType;
import com.piece.core.framework.support.convert.Convert;
import com.piece.core.framework.support.response.AjaxResponse;
import com.piece.core.framework.util.basic.I18nUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@RestController
@Api(tags = {"网站配置管理"})
@RequestMapping("/api/site")
public class SysSiteController extends ControllerSupport {

    @Resource
    private TbSysConfigService tbSysConfigService;

    @Resource
    private SiteConfigSupport siteConfigSupport;

    @GetMapping("/load")
    @AclPermission(code = "tool:site:view")
    @ApiOperation(value = "生成站点表单数据")
    @ApiImplicitParam(name = "id", value = "参数主键")
    public AjaxResponse loadSite() {
        return success(applicationProperties.getOptions());
    }

    @SubmitPermission
    @PostMapping("/save")
    @AclPermission(code = "tool:site:edit")
    @ApiOperation(value = "保存参数表单数据")
    @ApiImplicitParam(value = "参数表单", dataTypeClass = TbSysConfig.class, type = "body")
    public AjaxResponse saveSite() {
        Map<String, Object> option = new HashMap<>();
        try {
            initMap(option);
            TbSysConfig config = null;
            for (Map.Entry entry : option.entrySet()) {
                String key = Convert.toStr(entry.getKey());
                String value = Convert.toStr(entry.getValue(), "");
                config = tbSysConfigService.findByConfigKey(key);
                if (null == config) {
                    config = new TbSysConfig();
                    config.setConfigName("");
                    config.setConfigKey(key);
                    config.setConfigValue(value);
                    config.setConfigType(OptionType.LEAF.getCode());
                } else {
                    config.setConfigValue(value);
                }
                tbSysConfigService.insertOrUpdate(config);
                // 刷新站点变量
                siteConfigSupport.reload(config);
            }

            return success(I18nUtil.message(ExceptionConstants.SAVE_SUCCESS), null);
        } catch (Exception e) {
            return error(I18nUtil.message(ExceptionConstants.SAVE_FAILURE), e.getMessage());
        }
    }
}
